package com.mlethe.library.multi.api;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import androidx.annotation.NonNull;

import com.alipay.sdk.app.PayTask;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ProductDetails;
import com.android.billingclient.api.ProductDetailsResponseListener;
import com.android.billingclient.api.QueryProductDetailsParams;
import com.android.billingclient.api.QueryProductDetailsResult;
import com.mlethe.library.multi.api.entity.AliPayResult;
import com.mlethe.library.multi.api.listener.Callback;
import com.mlethe.library.multi.api.listener.OnActionCallback;
import com.mlethe.library.multi.api.listener.OnActionListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mobileqq.openpay.api.IOpenApi;
import com.tencent.mobileqq.openpay.constants.OpenConstants;
import com.tencent.mobileqq.openpay.data.pay.PayApi;
import com.unionpay.UPPayAssistEx;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付
 *
 * @author Mlethe
 * @date 2021/5/19
 */
public final class PayAction {
    /**
     * 支付方式
     */
    private final MultiMedia mMultiMedia;
    /**
     * 支付监听
     */
    private OnActionListener mListener;
    /**
     * 微信、QQ的appId
     */
    private String appId;
    /**
     * 微信、QQ钱包商户号id
     */
    private String merchantId;
    /**
     * 微信支付预支付交易会话ID
     * QQ钱包的预支付会话标识，具体值请传入调用统一下单接口后返回的“prepay_id”的值，注：参与签名参数key为“tokenId”,如“tokenId=8888888”
     */
    private String prepayId;
    /**
     * 微信支付、QQ钱包随机字符串
     */
    private String nonceStr;
    /**
     * 微信支付、QQ钱包时间戳，单位：秒
     */
    private long timeStamp;
    /**
     * 微信支付固定值Sign=WXPay
     */
    private String packageValue = "Sign=WXPay";
    /**
     * 微信支付、QQ钱包签名
     */
    private String sign;
    /**
     * 微信支付其他参数
     */
    private String extData;
    /**
     * 支付宝订单信息
     */
    private String orderInfo;
    /**
     * 支付宝二维码链接（监听事件无效）
     */
    private String qrcode;
    /**
     * 支付宝签约链接（监听事件无效）
     */
    private String signingLink;
    /**
     * 支付宝url支付链接（监听事件无效）
     */
    private String url;
    /**
     * 支付宝H5支付链接（WebViewClient重写shouldOverrideUrlLoading()方法）
     */
    private String interceptorWithUrl;
    /**
     * QQ钱包支付序号,用于标识此次支付
     */
    private String serialNumber;
    /**
     * QQ钱包支付结果回调给urlscheme为callbackScheme的activity
     */
    private String callbackScheme;
    /**
     * QQ钱包手Q公众帐号id.参与支付签名
     */
    private String pubAcc;
    /**
     * QQ钱包支付完成页面，展示给用户的提示语：提醒关注公众帐号
     */
    private String pubAccHint;
    /**
     * QQ钱包签名类型，使用的加密方式，默认为"HMAC-SHA1"
     */
    private String signType = "HMAC-SHA1";
    /**
     * 云闪付交易流水号
     */
    private String tn;
    /**
     * Google Play 商品id
     */
    private String productId;
    /**
     * 指定一个可选的混淆字符串，该字符串与应用程序中购买者的用户帐户唯一关联。(Google Play)
     * <p>
     * 如果您传递此值，Google Play 可以使用它来检测异常活动，例如许多设备在短时间内使用同一帐户进行购买。
     * 请勿使用此字段以明文形式存储任何个人身份信息 （PII），例如电子邮件。尝试在此字段中存储 PII 将导致购买被阻止。
     * Google Play 建议您使用加密或单向哈希来生成要发送到 Google Play 的混淆标识符。
     */
    private String obfuscatedAccountId;

    public PayAction(MultiMedia media) {
        this.mMultiMedia = media;
    }

    /**
     * 支付回调
     *
     * @param listener
     * @return
     */
    public PayAction setCallback(OnActionListener listener) {
        this.mListener = listener;
        return this;
    }

    /**
     * 微信、QQ的appId
     *
     * @param appId
     * @return
     */
    public PayAction setAppId(String appId) {
        this.appId = appId;
        return this;
    }

    /**
     * 微信、QQ钱包商户号id
     * 微信支付的 partnerId
     * QQ支付的 bargainorId
     *
     * @param merchantId 商户号id
     * @return
     */
    public PayAction setMerchantId(String merchantId) {
        this.merchantId = merchantId;
        return this;
    }

    /**
     * 微信支付预支付交易会话ID、QQ钱包支付序号,用于标识此次支付
     * QQ钱包的预支付会话标识，具体值请传入调用统一下单接口后返回的“prepay_id”的值，注：参与签名参数key为“tokenId”,如“tokenId=8888888”
     *
     * @param prepayId 支付序号
     * @return
     */
    public PayAction setPrepayId(String prepayId) {
        this.prepayId = prepayId;
        return this;
    }

    /**
     * 微信支付、QQ钱包随机字符串
     *
     * @param nonceStr 随机字符串
     * @return
     */
    public PayAction setNonceStr(String nonceStr) {
        this.nonceStr = nonceStr;
        return this;
    }

    /**
     * 微信支付、QQ钱包时间戳
     *
     * @param timeStamp 时间戳（单位：秒）
     * @return
     */
    public PayAction setTimeStamp(long timeStamp) {
        this.timeStamp = timeStamp;
        return this;
    }

    /**
     * 微信支付扩展字段
     *
     * @param packageValue
     * @return
     */
    public PayAction setPackageValue(String packageValue) {
        this.packageValue = packageValue;
        return this;
    }

    /**
     * 微信支付、QQ钱包签名
     *
     * @param sign 签名
     * @return
     */
    public PayAction setSign(String sign) {
        this.sign = sign;
        return this;
    }

    /**
     * 微信支付其他参数
     *
     * @param extData
     * @return
     */
    public PayAction setExtData(String extData) {
        this.extData = extData;
        return this;
    }

    /**
     * 支付宝订单信息
     *
     * @param orderInfo
     */
    public PayAction setOrderInfo(String orderInfo) {
        this.orderInfo = orderInfo;
        return this;
    }

    /**
     * 支付宝二维码链接（监听事件无效）
     *
     * @param qrcode
     * @return
     */
    public PayAction setQrcode(String qrcode) {
        this.qrcode = qrcode;
        return this;
    }

    /**
     * 支付宝签约链接（监听事件无效）
     *
     * @param signingLink
     * @return
     */
    public PayAction setSigningLink(String signingLink) {
        this.signingLink = signingLink;
        return this;
    }

    /**
     * 支付宝url支付链接（监听事件无效）
     *
     * @param url
     */
    public PayAction setUrl(String url) {
        this.url = url;
        return this;
    }

    /**
     * 支付宝H5支付链接（WebViewClient重写shouldOverrideUrlLoading()方法）
     *
     * @param url
     */
    public PayAction setInterceptorWithUrl(String url) {
        this.interceptorWithUrl = url;
        return this;
    }

    /**
     * QQ钱包支付序号,用于标识此次支付
     *
     * @param serialNumber
     * @return
     */
    public PayAction setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
        return this;
    }

    /**
     * QQ钱包支付结果回调给urlscheme为callbackScheme的activity
     *
     * @param callbackScheme
     * @return
     */
    public PayAction setCallbackScheme(String callbackScheme) {
        this.callbackScheme = callbackScheme;
        return this;
    }

    /**
     * QQ钱包手Q公众帐号id.参与支付签名
     *
     * @param pubAcc
     * @return
     */
    public PayAction setPubAcc(String pubAcc) {
        this.pubAcc = pubAcc;
        return this;
    }

    /**
     * QQ钱包支付完成页面，展示给用户的提示语：提醒关注公众帐号
     *
     * @param pubAccHint
     * @return
     */
    public PayAction setPubAccHint(String pubAccHint) {
        this.pubAccHint = pubAccHint;
        return this;
    }

    /**
     * QQ钱包签名类型，使用的加密方式，默认为"HMAC-SHA1"
     *
     * @param signType 签名类型，使用的加密方式，默认为"HMAC-SHA1"
     * @return
     */
    public PayAction setSignType(String signType) {
        this.signType = signType;
        return this;
    }

    /**
     * 云闪付交易流水号
     *
     * @param tn 交易流水号
     * @return
     */
    public PayAction setTn(String tn) {
        this.tn = tn;
        return this;
    }

    /**
     * Google Play 商品id
     *
     * @param productId 商品id
     * @return
     */
    public PayAction setProductId(String productId) {
        this.productId = productId;
        return this;
    }

    /**
     * 指定一个可选的混淆字符串，该字符串与应用程序中购买者的用户帐户唯一关联。(Google Play)
     * <p>
     * 如果您传递此值，Google Play 可以使用它来检测异常活动，例如许多设备在短时间内使用同一帐户进行购买。
     * 请勿使用此字段以明文形式存储任何个人身份信息 （PII），例如电子邮件。尝试在此字段中存储 PII 将导致购买被阻止。
     * Google Play 建议您使用加密或单向哈希来生成要发送到 Google Play 的混淆标识符。
     *
     * @param obfuscatedAccountId 唯一的值
     * @return
     */
    public PayAction setObfuscatedAccountId(String obfuscatedAccountId) {
        this.obfuscatedAccountId = obfuscatedAccountId;
        return this;
    }

    /**
     * 支付
     *
     * @param activity
     * @return true 启动成功，false 启动失败
     * 支付宝interceptorWithUrl支付返回H5是否拦截：true 已拦截，false 未拦截
     */
    public boolean pay(Activity activity) {
        OnActionListener listener = mListener;
        mListener = null;
        MultiApi instance = MultiApi.getInstance();
        Context context = instance.getContext();
        if (context == null) {
            onFailure(instance, listener, -8000, "MultiApi未初始化");
            return false;
        }
        if (MultiMedia.WECHAT == mMultiMedia) {
            // 微信
            IWXAPI api = instance.getWXApi();
            if (api == null) {
                onFailure(instance, listener, -8005, context.getString(R.string.multi_api_not_initialized_successfully));
                return false;
            } else {
                if (!instance.isInstalled(mMultiMedia)) {
                    // 未安装微信
                    onFailure(instance, listener, -8001, context.getString(R.string.multi_api_app_not_installed));
                    return false;
                }
                Platform platForm = instance.getPlatForm(mMultiMedia);
                PayReq request = new PayReq();
                request.appId = appId != null && !appId.isEmpty() ? appId : platForm.getAppId();
                request.partnerId = merchantId;
                request.prepayId = prepayId;
                request.packageValue = packageValue;
                request.nonceStr = nonceStr;
                request.timeStamp = String.valueOf(timeStamp);
                request.sign = sign;
                request.extData = extData;
                String state = Util.buildState();
                request.transaction = state;
                OnActionCallback callback = new OnActionCallback(2, listener);
                callback.state = state;
                instance.setMultiMedia(mMultiMedia)
                        .setActionCallback(callback);
                try {
                    if (api.sendReq(request)) {
                        return true;
                    }
                    instance.e("WECHAT pay launch fail.");
                    instance.release();
                    onFailure(instance, listener, -8004, context.getString(R.string.multi_api_filter_logs_check_reason, "MicroMsg.SDK"));
                } catch (Throwable t) {
                    instance.e("WECHAT pay launch fail.", t);
                    instance.release();
                    onFailure(instance, listener, -8004, t.getMessage());
                }
            }
            return false;
        } else if (MultiMedia.ALIPAY == mMultiMedia) {
            // 支付宝
            if (orderInfo != null && !orderInfo.isEmpty()) {
                boolean postStatus = instance.postAsync(() -> {
                    Map<String, String> result;
                    try {
                        PayTask alipay = new PayTask(activity);
                        result = alipay.payV2(orderInfo, true);
                    } catch (Throwable t) {
                        instance.e("Alipay pay fail.", t);
                        onFailure(instance, listener, -8004, t.getMessage());
                        return;
                    }
                    final AliPayResult payResult = new AliPayResult(result);
                    int status = payResult.getResultStatus();
                    if (status == 9000) {
                        // 订单支付成功
                        instance.i("Alipay pay success. data=" + result);
                        Map<String, String> map = new HashMap<>();
                        map.put("memo", payResult.getMemo());
                        map.put("result", payResult.getResult());
                        onComplete(instance, listener, map);
                    } else if (status == 6001) {
                        // 用户中途取消
                        instance.i("Alipay pay cancel.");
                        onCancel(instance, listener);
                    } else {
                        /**
                         * 8000：正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
                         * 4000：订单支付失败
                         * 5000：重复请求
                         * 6001：用户中途取消
                         * 6002：网络连接出错
                         * 6004：支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
                         * 其它支付错误
                         */
                        instance.e("Alipay pay fail. code=" + status);
                        onFailure(instance, listener, status, context.getString(R.string.multi_api_unknown_error));
                    }
                });
                if (!postStatus) {
                    onFailure(instance, listener, -8007, context.getString(R.string.multi_api_request_initiation_failed));
                }
                return postStatus;
            } else if (qrcode != null && !qrcode.isEmpty()) {
                // 支付宝二维码链接支付
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Uri uri = Uri.parse("alipays://platformapi/startapp?saId=10000007&qrcode=" + qrcode);
                    intent.setData(uri);
                    activity.startActivity(intent);
                    return true;
                } catch (Throwable t) {
                    instance.e("Alipay pay launch fail.", t);
                    onFailure(instance, listener, -8001, context.getString(R.string.multi_api_app_not_installed));
                }
            } else if (signingLink != null && !signingLink.isEmpty()) {
                // 支付宝签约链接
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Uri uri = Uri.parse("alipays://platformapi/startapp?appId=60000157&appClearTop=false&startMultApp=YES&sign_params=" + signingLink);
                    intent.setData(uri);
                    activity.startActivity(intent);
                    return true;
                } catch (Throwable t) {
                    instance.e("Alipay pay launch fail.", t);
                    onFailure(instance, listener, -8001, context.getString(R.string.multi_api_app_not_installed));
                }
            } else if (url != null && !url.isEmpty()) {
                // 支付宝url支付链接
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Uri uri = Uri.parse("alipays://platformapi/startapp?appId=60000157&url=" + url);
                    intent.setData(uri);
                    activity.startActivity(intent);
                    return true;
                } catch (Throwable t) {
                    instance.e("Alipay pay launch fail.", t);
                    onFailure(instance, listener, -8001, context.getString(R.string.multi_api_app_not_installed));
                }
            } else if (interceptorWithUrl != null && !interceptorWithUrl.isEmpty()) {
                // H5唤起支付宝支付
                try {
                    PayTask payTask = new PayTask(activity);
                    return payTask.payInterceptorWithUrl(interceptorWithUrl, true, result -> {
                        int code = Integer.parseInt(result.getResultCode());
                        if (code == 9000) {
                            // 订单支付成功
                            instance.i("Alipay pay interceptor success. data=" + result.getReturnUrl());
                            Map<String, String> map = new HashMap<>();
                            map.put("returnUrl", result.getReturnUrl());
                            onComplete(instance, listener, map);
                        } else if (code == 6001) {
                            // 用户中途取消
                            instance.i("Alipay pay interceptor cancel.");
                            onCancel(instance, listener);
                        } else {
                            /**
                             * 8000：正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
                             * 4000：订单支付失败
                             * 5000：重复请求
                             * 6001：用户中途取消
                             * 6002：网络连接出错
                             * 6004：支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
                             * 其它支付错误
                             */
                            instance.e("Alipay pay interceptor fail. code=" + code);
                            onFailure(instance, listener, code, context.getString(R.string.multi_api_unknown_error));
                        }
                    });
                } catch (Throwable t) {
                    instance.e("Alipay pay interceptor fail.", t);
                    onFailure(instance, listener, -8004, t.getMessage());
                }
            } else {
                onFailure(instance, listener, -8003, context.getString(R.string.multi_api_parameter_error));
            }
            return false;
        } else if (MultiMedia.QQ_PAY == mMultiMedia) {
            // QQ钱包
            IOpenApi api = instance.getOpenApi();
            if (api == null) {
                onFailure(instance, listener, -8005, context.getString(R.string.multi_api_not_initialized_successfully));
                return false;
            } else {
                if (!instance.isInstalled(mMultiMedia)) {
                    // 未安装QQ
                    onFailure(instance, listener, -8001, context.getString(R.string.multi_api_app_not_installed));
                    return false;
                }
                if (!api.isMobileQQSupportApi(OpenConstants.API_NAME_PAY)) {
                    // QQ 不支持支付
                    onFailure(instance, listener, -8002, context.getString(R.string.multi_api_feature_not_supported));
                    return false;
                }
                Platform platForm = instance.getPlatForm(mMultiMedia);
                PayApi request = new PayApi();
                request.appId = appId != null && !appId.isEmpty() ? appId : platForm.getAppId();
                request.serialNumber = serialNumber;
                request.callbackScheme = callbackScheme;
                request.tokenId = prepayId;
                request.pubAcc = pubAcc;
                request.pubAccHint = pubAccHint;
                request.nonce = nonceStr;
                request.timeStamp = timeStamp;
                request.bargainorId = merchantId;
                request.sig = sign;
                request.sigType = signType;
                if (request.checkParams()) {
                    instance.setMultiMedia(mMultiMedia)
                            .setActionCallback(new OnActionCallback(2, listener));
                    try {
                        if (api.execApi(request)) {
                            return true;
                        }
                        instance.e("QQ pay launch fail.");
                        instance.release();
                        onFailure(instance, listener, -8004, context.getString(R.string.multi_api_failed_launch_app));
                    } catch (Throwable t) {
                        instance.e("QQ pay launch fail.", t);
                        instance.release();
                        onFailure(instance, listener, -8004, t.getMessage());
                    }
                } else {
                    instance.e("QQ pay params fail.");
                    onFailure(instance, listener, -8003, context.getString(R.string.multi_api_parameter_error));
                }
                return false;
            }
        } else if (MultiMedia.UNION_PAY == mMultiMedia) {
            // 云闪付
            if (tn != null && !tn.isEmpty()) {
                if (!instance.isInstalled(mMultiMedia)) {
                    // 未安装云闪付
                    onFailure(instance, listener, -8001, context.getString(R.string.multi_api_app_not_installed));
                    return false;
                }
                instance.setMultiMedia(mMultiMedia)
                        .setActionCallback(new OnActionCallback(2, listener));
                try {
                    UPPayAssistEx.startPay(activity, null, null, tn, "00");
                    return true;
                } catch (Throwable t) {
                    instance.e("UNION_PAY pay launch fail.", t);
                    instance.release();
                    onFailure(instance, listener, -8004, t.getMessage());
                }
            } else {
                onFailure(instance, listener, -8003, context.getString(R.string.multi_api_parameter_error));
            }
            return false;
        } else if (MultiMedia.GOOGLE == mMultiMedia) {
            // Google Play
            if (productId != null && !productId.isEmpty()) {
                BillingClient billingClient = instance.getBillingClient();
                if (billingClient == null) {
                    onFailure(instance, listener, -8005, context.getString(R.string.multi_api_not_initialized_successfully));
                    return false;
                }
                if (!instance.isInstalled(mMultiMedia)) {
                    onFailure(instance, listener, -8002, context.getString(R.string.multi_api_feature_not_supported));
                    return false;
                }
                instance.i("Google pay start connection.");
                return instance.startConnection(billingClient, false, new Callback<Object>() {
                    @Override
                    public void onSuccess(@NonNull Object data) {
                        try {
                            BillingResult supportedResult = billingClient.isFeatureSupported(BillingClient.FeatureType.PRODUCT_DETAILS);
                            if (supportedResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                                // 结算系统5支持
                                List<QueryProductDetailsParams.Product> productList = new ArrayList<>();
                                productList.add(QueryProductDetailsParams.Product.newBuilder()
                                        .setProductId(productId)
                                        .setProductType(BillingClient.ProductType.INAPP)
                                        .build());
                                QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()
                                        .setProductList(productList)
                                        .build();
                                instance.i("Google pay start queryProductDetails.");
                                billingClient.queryProductDetailsAsync(params, new ProductDetailsResponseListener() {
                                    @Override
                                    public void onProductDetailsResponse(@NonNull BillingResult billingResult, @NonNull QueryProductDetailsResult queryProductDetailsResult) {
                                        int responseCode = billingResult.getResponseCode();
                                        if (responseCode != BillingClient.BillingResponseCode.OK) {
                                            String message = billingResult.getDebugMessage();
                                            instance.e("Google pay fail queryProductDetails. code=" + responseCode + ", message=" + message);
                                            PayAction.this.onFailure(instance, listener, responseCode, message);
                                            return;
                                        }
                                        List<ProductDetails> list = queryProductDetailsResult.getProductDetailsList();
                                        if (list.isEmpty()) {
                                            instance.e("Google pay fail queryProductDetails. Product not found.");
                                            PayAction.this.onFailure(instance, listener, -9801, "Product not found.");
                                            return;
                                        }
                                        instance.i("Google pay success queryProductDetails.");
                                        try {
                                            List<BillingFlowParams.ProductDetailsParams> productDetailsParamsList = new ArrayList();
                                            for (ProductDetails item : list) {
                                                BillingFlowParams.ProductDetailsParams productDetailsParams = BillingFlowParams.ProductDetailsParams.newBuilder()
                                                        // retrieve a value for "productDetails" by calling queryProductDetailsAsync()
                                                        .setProductDetails(item)
                                                        .build();
                                                productDetailsParamsList.add(productDetailsParams);
                                            }
                                            // 启动 Google Play
                                            BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
                                                    .setProductDetailsParamsList(productDetailsParamsList)
                                                    .setObfuscatedAccountId(obfuscatedAccountId)
                                                    .build();
                                            instance.i("Google pay launch start.");
                                            // Launch the billing flow
                                            BillingResult launchResult = billingClient.launchBillingFlow(activity, billingFlowParams);
                                            int resultResponseCode = launchResult.getResponseCode();
                                            if (resultResponseCode != BillingClient.BillingResponseCode.OK) {
                                                String msg = launchResult.getDebugMessage();
                                                instance.e("Google pay launch fail. code->" + resultResponseCode + ", message=" + msg);
                                                PayAction.this.onFailure(instance, listener, resultResponseCode, msg);
                                                return;
                                            }
                                            instance.i("Google pay launch success.");
                                            // google Play 唤起成功
                                            instance.setMultiMedia(mMultiMedia)
                                                    .setActionCallback(new OnActionCallback(2, listener));
                                        } catch (Exception e) {
                                            String message = e.getMessage();
                                            if (message == null) {
                                                message = "";
                                            }
                                            PayAction.this.onFailure(instance, listener, -8004, message);
                                        }
                                    }
                                });
                            } else {
                                // 结算库版本4支持
                                instance.e("Google pay launch fail. Does not support settlement library versions below 5.");
                                PayAction.this.onFailure(instance, listener, -8002, context.getString(R.string.multi_api_feature_not_supported));
                            }
                        } catch (Exception e) {
                            String message = e.getMessage();
                            if (message == null) {
                                message = "";
                            }
                            PayAction.this.onFailure(instance, listener, -9900, message);
                        }
                    }

                    @Override
                    public void onFailure(int code, @NonNull String msg) {
                        instance.e("Google pay fail connection. code=" + code + ", message=" + msg);
                        PayAction.this.onFailure(instance, listener, code, msg);
                    }
                });
            } else {
                onFailure(instance, listener, -8003, context.getString(R.string.multi_api_parameter_error));
            }
            return false;
        } else {
            onFailure(instance, listener, -8002, context.getString(R.string.multi_api_feature_not_supported));
        }
        return false;
    }

    /**
     * 完成回调监听
     *
     * @param listener
     * @param map
     */
    private void onComplete(@NonNull MultiApi instance, OnActionListener listener, @NonNull Map<String, String> map) {
        if (listener == null) {
            return;
        }
        MultiMedia multiMedia = mMultiMedia;
        instance.post(() -> listener.onComplete(multiMedia, map));
    }

    /**
     * 取消回调监听
     *
     * @param listener
     */
    private void onCancel(@NonNull MultiApi instance, OnActionListener listener) {
        if (listener == null) {
            return;
        }
        MultiMedia multiMedia = mMultiMedia;
        instance.post(() -> listener.onCancel(multiMedia));
    }

    /**
     * 失败回调监听
     *
     * @param listener
     * @param code
     */
    private void onFailure(@NonNull MultiApi instance, OnActionListener listener, int code, String msg) {
        if (listener == null) {
            return;
        }
        MultiMedia multiMedia = mMultiMedia;
        instance.post(() -> listener.onFailure(multiMedia, code, msg));
    }
}
